//
//  JWBoJianDetailsVC.m
//  jinwang
//
//  Created by jzb on 2018/3/29.
//  Copyright © 2018年 jzb. All rights reserved.
//

#import "JWBoJianDetailsVC.h"
#import "JWBoJianDetailsCell.h"
#import "JWBoJianDetailsLikeCell.h"
#import "JWBoJianDetaildCommentCell.h"
#import "JWBoJianDetailsCommentModel.h"
#import <AVKit/AVKit.h>
#import <AVFoundation/AVFoundation.h>
#import "TopUpVC.h"
#import "JWBoJianGiftModel.h"
#import "JWBoJianGiftScrollView.h"

@interface JWBoJianDetailsVC ()<AVAudioPlayerDelegate,UITextViewDelegate,UIGestureRecognizerDelegate,UIWebViewDelegate>
{
    TYAlertController *_alertController;
}
@property (nonatomic,strong) JWBoJianDetailsCell *DetailsCell;
@property (nonatomic,strong) JWBoJianDetailsLikeCell *LikeCell;
@property (nonatomic,strong) JWBoJianDetaildCommentCell *CommentCell;

@property (nonatomic,assign) int page;

@property (nonatomic,strong) NSMutableArray *ListmodelArr,*giftListArr;
@property (nonatomic,strong) NSMutableArray *praiseListArr;
@property (nonatomic,strong) NSMutableArray *CommentListArr;

@property (nonatomic,strong)BJDynamicSnapshotModel *SnapshotModel;
@property (nonatomic,strong)AVAudioPlayer *audioPlayer;

@property (nonatomic,strong)UITextView *CommentTextView;
@property (nonatomic,strong)UILabel *placeholderLabel;//提示文字
@property (nonatomic,strong)NSString *comment_type;//评论类型0文字1语音
@property (nonatomic,strong)NSString *parent_id;//回复评论id
@property (nonatomic,strong)UIButton *tapeBtn,*sendBtn;
@property (nonatomic,strong)UIView *textBottomLine,*GiftBGView;
@property (nonatomic,strong)JWBoJianGiftModel *GiftModel;

@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic, strong) AVPlayerViewController *playerView;

@property (nonatomic,strong)UIWebView *JiaWenWebView;


@end

@implementation JWBoJianDetailsVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"博见";
    _page = 1;
    _comment_type = @"0";
    [self setUpTableView];
    [self makeUrl_post_postInfo];
    [self makeUrl_postBJ_praiseList];
    [self makeUrl_postBJ_commentList];
    [self makeUrl_postBJ_giftList];
    //监听键盘收回
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}

//配置tableView
-(void)setUpTableView{
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.tableView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight - 55);
    self.tableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    
    //注册cell
    self.tableView.estimatedRowHeight = UITableViewAutomaticDimension;
    [self registerCellWithCellClassArray:@[NSStringFromClass([JWBoJianDetailsCell class])]];
    [self registerCellWithCellClassArray:@[NSStringFromClass([JWBoJianDetailsLikeCell class])]];
    [self registerCellWithCellClassArray:@[NSStringFromClass([JWBoJianDetaildCommentCell class])]];
//
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{

        //        [self JsonRequest];
        [self makeUrl_post_postInfo];
        [self makeUrl_postBJ_praiseList];
        [self makeUrl_postBJ_commentList];
    }];
    //上啦加载更多
    self.tableView.mj_footer  = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{

        _page++;
        [self makeUrl_postBJ_commentList];
    }];
    [self.tableView.mj_footer endRefreshing];
    
    UIView *commentBGView = [[UIView alloc]initWithFrame:CGRectMake(0, kScreenHeight - 55-64, kScreenWidth, 55)];
    [self.view addSubview:commentBGView];
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, .5)];
    lineView.backgroundColor = kRGBColor(230, 230, 230);
    [commentBGView addSubview:lineView];
    _CommentTextView = [[UITextView alloc]initWithFrame:CGRectMake(50, 12.5, kScreenWidth - 50-80, 30)];
    
//    text.backgroundColor = [UIColor purpleColor];
//    text.placeholder = @"说点什么吧";
//    [text setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
    [_CommentTextView setValue:[UIFont boldSystemFontOfSize:15] forKeyPath:@"_placeholderLabel.font"];
    _CommentTextView.font = [UIFont systemFontOfSize:15];
    _CommentTextView.delegate = self;
    [commentBGView addSubview:_CommentTextView];
    
    _placeholderLabel = [[UILabel alloc] initWithFrame:CGRM(10, 18, 750-100, 30)];
    _placeholderLabel.text = @"说点什么吧";
    _placeholderLabel.font = [UIFont systemFontOfSize:15.f];
    _placeholderLabel.textColor = [UIColor lightGrayColor];
    _placeholderLabel.numberOfLines = 0;
    [_placeholderLabel sizeToFit];
    [_CommentTextView addSubview:_placeholderLabel];
    
    if (_CommentTextView.text.length > 0) {
        
        _placeholderLabel.hidden = YES;
        
    }else{
        
        _placeholderLabel.hidden = NO;
    }
    
    _sendBtn = [[UIButton alloc]initWithFrame:CGRectMake(kScreenWidth - 70, 10, 55, 35)];
    
    _sendBtn.backgroundColor = UIColorHex(0xEEA72B);
    
    [_sendBtn setTitle:@"发送" forState:UIControlStateNormal];
    [_sendBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_sendBtn addTarget:self action:@selector(sendBtnOnclick:) forControlEvents:UIControlEventTouchUpInside];
    _sendBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    
    _sendBtn.layer.cornerRadius = 5.0;
    
    _textBottomLine = [[UIView alloc]initWithFrame:CGRectMake(50, 43.5, kScreenWidth - 50-80, 1)];
    _textBottomLine.backgroundColor = kRGBColor(230, 230, 230);
    [commentBGView addSubview:_textBottomLine];
    
    [commentBGView addSubview:_sendBtn];
    
    UIButton *yuyinBtn = [[UIButton alloc]initWithFrame:CGRectMake(15, 13, 30, 30)];
    
    [yuyinBtn setImage:[UIImage imageNamed:@"jw_bojian_xiangqing_yuyinIcon"] forState:UIControlStateNormal];
    [yuyinBtn addTarget:self action:@selector(yuyinBtnOnclick:) forControlEvents:UIControlEventTouchUpInside];
    [commentBGView addSubview:yuyinBtn];
    _tapeBtn = [[UIButton alloc]initWithFrame:CGRectMake(55, 10, kScreenWidth - 55 - 25, 35)];
    [_tapeBtn setTitle:@"按住说话" forState:UIControlStateNormal];
    [_tapeBtn setTitleColor:kRGBColor(80, 80, 80) forState:UIControlStateNormal];
    _tapeBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    _tapeBtn.backgroundColor = [UIColor whiteColor];
    _tapeBtn.hidden = YES;
    _tapeBtn.layer.cornerRadius = 4;
    _tapeBtn.layer.masksToBounds = YES;
    _tapeBtn.layer.borderColor = kRGBColor(120, 120, 120).CGColor;
    _tapeBtn.layer.borderWidth = .5;
    [commentBGView addSubview:_tapeBtn];
    
    _JiaWenWebView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth-20, 1)];
    _JiaWenWebView.delegate = self;
    _JiaWenWebView.scrollView.scrollEnabled = NO;
}
- (void)giftBGViewBuild{
    
    _GiftBGView = [[UIView alloc]initWithFrame:CGRM(0, 0, 750, 450)];
    _GiftBGView.backgroundColor = [UIColor whiteColor];
    
    JWBoJianGiftScrollView *giftScrollView = [[JWBoJianGiftScrollView alloc]initWithFrame:CGRM(0, 0, 750, 350)];
    giftScrollView.giftListArr = _giftListArr;
    giftScrollView.GiftBlcok = ^(JWBoJianGiftModel *model) {
        
        _GiftModel = model;
    };
    [_GiftBGView addSubview:giftScrollView];
    
    UIView *lineVeiw = [[UIView alloc]initWithFrame:CGRM(0, 350, 750, 2)];
    lineVeiw.backgroundColor = kRGBColor(240, 240, 240);
    [_GiftBGView addSubview:lineVeiw];
    
    NSString *yueStr = @"¥10000.00";
    CGSize size = CGSizeMake(300, 35);
    CGSize yueStrSize = [yueStr boundingRectWithSize:size options:NSStringDrawingUsesFontLeading|NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:16]} context:nil].size;
    UILabel *yueLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 365/2+3, yueStrSize.width, 35)];
    yueLabel.text = yueStr;
    yueLabel.textColor = kRGBColor(100, 100, 100);
    yueLabel.font = [UIFont systemFontOfSize:16];
    [_GiftBGView addSubview:yueLabel];

    UIButton *chongzhiBtn = [[UIButton alloc]initWithFrame:CGRectMake(yueStrSize.width+10, 365/2+3, 60, 35)];
    [chongzhiBtn setTitle:@"充值＞" forState:UIControlStateNormal];
    chongzhiBtn.tag = 2200;
    [chongzhiBtn addTarget:self action:@selector(giftBtnOnclick:) forControlEvents:UIControlEventTouchUpInside];
    [chongzhiBtn setTitleColor:kRGBColor(100, 100, 100) forState:UIControlStateNormal];
    chongzhiBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [_GiftBGView addSubview:chongzhiBtn];
    
    UIButton *presentBtn = [[UIButton alloc]initWithFrame:CGRM(750-170, 365, 150, 70)];
    presentBtn.backgroundColor = UIColorHex(0xEEA72B);
    [presentBtn setTitle:@"赠送" forState:UIControlStateNormal];
    presentBtn.tag = 2201;
    [presentBtn addTarget:self action:@selector(giftBtnOnclick:) forControlEvents:UIControlEventTouchUpInside];
    [presentBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    presentBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    presentBtn.layer.cornerRadius = 5.0;
    presentBtn.layer.masksToBounds = YES;
    [_GiftBGView addSubview:presentBtn];
    
}
#pragma mark -UITableViewDelegate,UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (section == 2) {
         return _CommentListArr.count;
    }else{
        return 1;
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        self.DetailsCell = [tableView dequeueReusableCellWithIdentifier:[JWBoJianDetailsCell getCellReuseIdentifier]];
        self.DetailsCell.contentView.backgroundColor = [UIColor clearColor];
        self.DetailsCell.model = _SnapshotModel;
        self.DetailsCell.upDownBtn.backgroundColor = [UIColor whiteColor];
        [self.DetailsCell.GiftBtn addTarget:self action:@selector(DetailsCellBtnOnclick:) forControlEvents:UIControlEventTouchUpInside];
        if (_SnapshotModel.post_content.length > 0){
            if ([_SnapshotModel.post_type integerValue] == 0) {
                //快照
                CGFloat height = [self cellContentViewWith:self.DetailsCell.imgsBGView.width withModel:_SnapshotModel];
                self.DetailsCell.webViewHeight.constant = height;
                WBImageView *webView = [[WBImageView alloc]initWithFrame:CGRectMake(0, 0, self.DetailsCell.imgsBGView.width, height)];
                NSArray* array = [_SnapshotModel.post_content componentsSeparatedByString:@","];
                webView.imageUrls = array;
                
                [self.DetailsCell.imgsBGView addSubview:webView];
                
            }else if ([_SnapshotModel.post_type integerValue] == 1){
                //爱拍
                self.DetailsCell.webViewHeight.constant = 150;
                UIButton *imageVeiwBtn = [[UIButton alloc]initWithFrame:CGRectMake(self.DetailsCell.imgsBGView.width/3, 0, self.DetailsCell.imgsBGView.width/3, 150)];
                NSArray* array = [_SnapshotModel.post_content componentsSeparatedByString:@","];
                UIImage * img = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:array[0]]]];
                [imageVeiwBtn setImage:img forState:UIControlStateNormal];
                [imageVeiwBtn addTarget:self action:@selector(MovieBtnOnckick:) forControlEvents:UIControlEventTouchUpInside];
//                [imageVeiw sd_setImageWithURL:[NSURL URLWithString:array[0]] placeholderImage:[UIImage imageNamed:@""]];
                [self.DetailsCell.imgsBGView addSubview:imageVeiwBtn];
                UIImageView *iconImg = [[UIImageView alloc]initWithFrame:CGRectMake(imageVeiwBtn.width/2-8, imageVeiwBtn.height/2-10, 16, 20)];
                iconImg.image = [UIImage imageNamed:@"jw_bj_aipaiBofangImg"];
                [imageVeiwBtn addSubview:iconImg];
            }else if ([_SnapshotModel.post_type integerValue] == 2){
                //佳文
//                self.DetailsCell.webViewHeight.constant = _JiaWenWebView.height;
                [self.DetailsCell.imgsBGView addSubview:_JiaWenWebView];
            }
        }
        
        [self.DetailsCell.LikeBtn addTarget:self action:@selector(DetailsCellBtnOnclick:) forControlEvents:UIControlEventTouchUpInside];
        return self.DetailsCell;
    }else if (indexPath.section == 1){
        self.LikeCell = [tableView dequeueReusableCellWithIdentifier:[JWBoJianDetailsLikeCell getCellReuseIdentifier]];
        self.LikeCell.contentView.backgroundColor = [UIColor clearColor];
        self.LikeCell.LikeView.hidden = YES;
        
        if ([_praiseListArr componentsJoinedByString:@"、"].length > 0) {
            self.LikeCell.LikeView.hidden = NO;
            self.LikeCell.likeLabel.text = [_praiseListArr componentsJoinedByString:@"、"];
        }else{
            
            self.LikeCell.LikeView.hidden = YES;
        }
        return self.LikeCell;
        
    }else{
        self.CommentCell = [tableView dequeueReusableCellWithIdentifier:[JWBoJianDetaildCommentCell getCellReuseIdentifier]];
        self.CommentCell.contentView.backgroundColor = [UIColor clearColor];
        
        JWBoJianDetailsCommentModel *model = _CommentListArr[indexPath.row];
        self.CommentCell.model = model;
        
        if([model.comment_type integerValue] == 1){
            
            [self.CommentCell.yuyingBtn addTarget:self action:@selector(yuyingPlay:) forControlEvents:UIControlEventTouchUpInside];
            self.CommentCell.yuyingBtn.tag = 3000+indexPath.row;
        }else if ([model.comment_type integerValue] == 0){
            
            //单击的手势
            UITapGestureRecognizer *click = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(Comment_contentLabelTap:)];

            //点击几次后触发事件响应，默认为：1
            click.numberOfTapsRequired = 1;
            //需要几个手指点击时触发事件，默认：1
            click.numberOfTouchesRequired = 1;
            
            self.CommentCell.comment_content.userInteractionEnabled = YES;

            [self.CommentCell.comment_content addGestureRecognizer:click];
            
        }
        CGFloat Comment_height = 0;
        if (model.reply.count > 0) {
            
            self.CommentCell.Other_commentBGView.hidden = NO;
            
            for (UIView *view in self.CommentCell.Other_commentBGView.subviews) {
                
                [view removeFromSuperview];
            }
            CGFloat height = 0;
            CGFloat comment_contentSize = 0;
            for (int i = 0; i < model.reply.count; i++) {
                
                NSDictionary *replyDic = model.reply[i];
                NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:14],};
                
                NSString *user_nickname = [NSString stringWithFormat:@"%@:",[replyDic objectForKey:@"user_nickname"]];
                NSString *comment_content = [replyDic objectForKey:@"comment_content"];
                
                CGSize user_nicknameSize = [user_nickname boundingRectWithSize:CGSizeMake(100, MAXFLOAT)
                                                    options:NSStringDrawingTruncatesLastVisibleLine attributes:attributes context:nil].size;
                CGSize size = CGSizeMake(self.CommentCell.Other_commentBGView.width-user_nicknameSize.width-5, 100000);//设置高度宽度的最大限度
                
                if ([[replyDic objectForKey:@"comment_type"] integerValue] == 0) {
                    
                     comment_contentSize = [comment_content boundingRectWithSize:size options:NSStringDrawingUsesFontLeading|NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14]} context:nil].size.height+5;
                    
                }else if ([[replyDic objectForKey:@"comment_type"] integerValue] == 1){
                    
                    comment_contentSize = 35;
                }
                
                height = height+comment_contentSize;
                
                Comment_height = height-comment_contentSize+8;
                
                UILabel *nicknameLabel = [[UILabel alloc]initWithFrame:CGRectMake(5, Comment_height+2, user_nicknameSize.width, user_nicknameSize.height)];
                
                nicknameLabel.textColor = [UIColor blackColor];
                nicknameLabel.font = [UIFont systemFontOfSize:14];
                nicknameLabel.text = user_nickname;
                [self.CommentCell.Other_commentBGView addSubview:nicknameLabel];
                
                if ([[replyDic objectForKey:@"comment_type"] integerValue] == 0) {
                    
                    UILabel *comment_contentLabel = [[UILabel alloc]initWithFrame:CGRectMake(user_nicknameSize.width+5,Comment_height, self.CommentCell.Other_commentBGView.width-user_nicknameSize.width-5, comment_contentSize)];
                    comment_contentLabel.numberOfLines = 0;
                    comment_contentLabel.text = comment_content;
                    comment_contentLabel.font = [UIFont systemFontOfSize:14];
                    [self.CommentCell.Other_commentBGView addSubview:comment_contentLabel];
                    
                }else if ([[replyDic objectForKey:@"comment_type"] integerValue] == 1){
                    
                    UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(user_nicknameSize.width+10,Comment_height+5, 100, 30)];
                    
                    button.backgroundColor = [UIColor orangeColor];
                    
                    [self.CommentCell.Other_commentBGView addSubview:button];
                }
            }
            self.CommentCell.Other_commentBGViewHeight.constant = height+16;
        }else{
            self.CommentCell.Other_commentBGView.hidden = YES;
            self.CommentCell.Other_commentBGViewHeight.constant = 0;
            
        }
        return self.CommentCell;
    }
    
}
//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//
//    if (indexPath.section == 0) {
//        NSArray* array = [_SnapshotModel.post_content componentsSeparatedByString:@","];
//        if (array.count > 0) {
//
//            return 150-17 + [self cellContentViewWith:self.DetailsCell.imgsBGView.width withModel:_SnapshotModel];
//        }else{
//
//            return 150;
//        }
//    }else if(indexPath.section == 1){
//        NSString *string = [_praiseListArr componentsJoinedByString:@"、"];
//        if (string.length > 0) {
//             CGSize size = CGSizeMake(kScreenWidth - 53, MAXFLOAT);//设置高度宽度的最大限度
//            CGRect rect = [string boundingRectWithSize:size options:NSStringDrawingUsesFontLeading|NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:15]} context:nil];
//
//             return rect.size.height + 18;
//        }else{
//
//            return 0;
//        }
//
//    }else{
//
//        JWBoJianDetailsCommentModel *model = _CommentListArr[indexPath.row];
//
//        CGSize size = CGSizeMake(kScreenWidth - 76, MAXFLOAT);//设置高度宽度的最大限度
//        CGRect rect = [model.comment_content boundingRectWithSize:size options:NSStringDrawingUsesFontLeading|NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14]} context:nil];
//
//        if (model.reply.count == 0 && [model.comment_type integerValue] == 0) {
//
//            return 0;
//
//        }else{
//
//            CGFloat Comment_height = 0;
//            CGFloat height = 0;
//            CGFloat comment_contentSize = 0;
//            for (int i = 0; i < model.reply.count; i++) {
//
//                NSDictionary *replyDic = model.reply[i];
//                NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:14],};
//
//                NSString *user_nickname = [NSString stringWithFormat:@"%@:",[replyDic objectForKey:@"user_nickname"]];
//                NSString *comment_content = [replyDic objectForKey:@"comment_content"];
//
//                CGSize user_nicknameSize = [user_nickname boundingRectWithSize:CGSizeMake(100, MAXFLOAT)
//                                                                       options:NSStringDrawingTruncatesLastVisibleLine attributes:attributes context:nil].size;
//                CGSize size = CGSizeMake(self.CommentCell.Other_commentBGView.width-user_nicknameSize.width-5, 100000);//设置高度宽度的最大限度
//
//                if ([[replyDic objectForKey:@"comment_type"] integerValue] == 0) {
//
//                    comment_contentSize = [comment_content boundingRectWithSize:size options:NSStringDrawingUsesFontLeading|NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14]} context:nil].size.height+5;
//
//                }else if ([[replyDic objectForKey:@"comment_type"] integerValue] == 1){
//
//                    comment_contentSize = 35;
//                }
//
//                height = height+comment_contentSize;
//
//                Comment_height = height-comment_contentSize+8;
//
//            }
//
//            return height+16;
//
//        }
//    }
//}
- (CGFloat)cellContentViewWith:(CGFloat)width withModel:(BJDynamicSnapshotModel *)model
{
    
    CGFloat Height = (width - 20)/3 + 5;
    CGFloat CellHeight = 0;
    
//    CGSize size = CGSizeMake(kScreenWidth - 30, MAXFLOAT);//设置高度宽度的最大限度
//    CGRect rect = [model.post_title boundingRectWithSize:size options:NSStringDrawingUsesFontLeading|NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14]} context:nil];

    NSArray* array = [model.post_content componentsSeparatedByString:@","];
    if (array.count % 3 > 0) {

        CellHeight = Height*(array.count/3+1);

    }else{

        CellHeight = Height*(array.count/3);
    }

//    return CellHeight + rect.size.height;
    return CellHeight ;
}
//- (void)webViewDidFinishLoad:(UIWebView *)webView {
//
//    if (!webView.isLoading) {
//        CGFloat height = [[_JiaWenWebView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"] floatValue];
//
//        NSLog(@"---=-=-=-=>>%lf",height);
//
//        NSString *js=@"var script = document.createElement('script');"
//        "script.type = 'text/javascript';"
//        "script.text = \"function ResizeImages() { "
//        "var myimg,oldwidth;"
//        "var maxwidth = %f;"
//        "for(i=0;i <document.images.length;i++){"
//        "myimg = document.images[i];"
//        "if(myimg.width > maxwidth){"
//        "oldwidth = myimg.width;"
//        "myimg.width = %f;"
//        "}"
//        "}"
//        "}\";"
//        "document.getElementsByTagName('head')[0].appendChild(script);";
//        js=[NSString stringWithFormat:js,self.DetailsCell.imgsBGView.width,self.DetailsCell.imgsBGView.width-10];
//        [webView stringByEvaluatingJavaScriptFromString:js];
//        [webView stringByEvaluatingJavaScriptFromString:@"ResizeImages();"];
//
//        _JiaWenWebView.frame = CGRectMake(0, 0, self.DetailsCell.imgsBGView.width, height);
//        self.DetailsCell.webViewHeight.constant = _JiaWenWebView.height;
//
//        UIScrollView *tempView = (UIScrollView *)[_JiaWenWebView.subviews objectAtIndex:0];
//        tempView.scrollEnabled = NO;
//        [self.tableView reloadData];
//
////        NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:0];
////        [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
//    }
//}
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    //获取到webview的高度
    CGFloat height = [[_JiaWenWebView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue]+10;
    _JiaWenWebView.frame = CGRectMake(_JiaWenWebView.frame.origin.x,_JiaWenWebView.frame.origin.y, kScreenWidth-20, height);
    self.DetailsCell.webViewHeight.constant = _JiaWenWebView.height;
//    NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:0];
//    [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
    [self.tableView reloadData];
}
- (void)DetailsCellBtnOnclick:(UIButton *)sender{
    
    if (sender.tag == 1001) {
        sender.userInteractionEnabled=NO;
        [sender setImage:[UIImage imageNamed:@"jw_bj_like_sel"] forState:UIControlStateNormal];
        [self makeUrl_postBJ_postPraise];
    }else if (sender.tag == 1002){
        
        NSLog(@"sadfasdfasdf");
        
        _alertController = [TYAlertController alertControllerWithAlertView:_GiftBGView preferredStyle:TYAlertControllerStyleActionSheet];
        _alertController.backgoundTapDismissEnable = YES;
        [self presentViewController:_alertController animated:YES completion:nil];
        
    }
    
}
- (void)giftBtnOnclick:(UIButton *)sender{
    
    [_alertController dismissViewControllerAnimated:NO];
    if (sender.tag == 2200) {
        
        TopUpVC *VC = [TopUpVC new];
        
        [self.navigationController pushViewController:VC animated:YES];
        
    }else if (sender.tag == 2201){
        NSLog(@"-=-=-=>>>%@",_GiftModel);
        if (_GiftModel.gift_name.length > 0) {
            
            [self makeUrl_postBJ_toGift];
            
        }else{
            
            [self showCenterMessage:@"请选择您要赠送的礼物"];
        }

    }
}

- (void)sendBtnOnclick:(UIButton *)sender{
    [_CommentTextView resignFirstResponder];
    if (kStringIsEmpty(self.CommentTextView.text)) {
        [self showBottomMessag:@"请输入您的评论"];
        return;
    }
    
    [self makeUrl_postBJ_postComment];
}
- (void)yuyinBtnOnclick:(UIButton *)sender{
    
    sender.selected = !sender.selected;
    
    if (sender.selected) {
        _tapeBtn.hidden = NO;
        _sendBtn.hidden = YES;
        _textBottomLine.hidden = YES;
        _CommentTextView.hidden = YES;
        [sender setImage:[UIImage imageNamed:@"jw_bojian_jianpanIcon"] forState:UIControlStateNormal];
    }else{
        _tapeBtn.hidden = YES;
        _sendBtn.hidden = NO;
        _textBottomLine.hidden = NO;
        _CommentTextView.hidden = NO;
        [sender setImage:[UIImage imageNamed:@"jw_bojian_xiangqing_yuyinIcon"] forState:UIControlStateNormal];
    }
}
- (void)MovieBtnOnckick:(UIButton *)sender{
    NSArray* array = [_SnapshotModel.post_content componentsSeparatedByString:@","];
    NSURL *url = [NSURL URLWithString:array[1]];
    AVPlayerViewController *play = [[AVPlayerViewController alloc] init];
    
//    play.player = [[AVPlayer alloc] initWithURL:url];
    play.player = [AVPlayer playerWithURL:url];
    
    // 是否显示视频播放控制控件默认YES
    play.showsPlaybackControls = YES;
    
    // 设置视频播放界面的尺寸播放选项
    // AVLayerVideoGravityResizeAspect   默认 不进行比例缩放 以宽高中长的一边充满为基准
    // AVLayerVideoGravityResizeAspectFill 不进行比例缩放 以宽高中短的一边充满为基准
    // AVLayerVideoGravityResize     进行缩放充满屏幕
    play.videoGravity = @"AVLayerVideoGravityResizeAspect";
    
    // 是否支持画中画 默认YES
    play.allowsPictureInPicturePlayback = YES;
    
    [play.player play];

    [self presentViewController:play animated:YES completion:nil];

//    视频播放的url
//    NSURL *playerURL = [NSURL URLWithString:playString];
    
//    //初始化
//    self.playerView = [[AVPlayerViewController alloc]init];
//
//    //AVPlayerItem 视频的一些信息  创建AVPlayer使用的
//    AVPlayerItem *item = [[AVPlayerItem alloc]initWithURL:url];
//
//    //通过AVPlayerItem创建AVPlayer
//    self.player = [[AVPlayer alloc]initWithPlayerItem:item];
//
//    //给AVPlayer一个播放的layer层
//    AVPlayerLayer *layer = [AVPlayerLayer playerLayerWithPlayer:self.player];
//
//    layer.frame = CGRectMake(0, 100, self.view.frame.size.width, 200);
//
//    layer.backgroundColor = [UIColor greenColor].CGColor;
//
//    //设置AVPlayer的填充模式
//    layer.videoGravity = AVLayerVideoGravityResize;
//
//    [self.view.layer addSublayer:layer];
//
//    //设置AVPlayerViewController内部的AVPlayer为刚创建的AVPlayer
//    self.playerView.player = self.player;
//
//    //关闭AVPlayerViewController内部的约束
//    self.playerView.view.translatesAutoresizingMaskIntoConstraints = YES;
//
    
}
- (void)Comment_contentLabelTap:(UITapGestureRecognizer *)gesture{
    
    //获得当前手势触发的在UITableView中的坐标
    CGPoint location = [gesture locationInView:self.tableView];
    //获得当前坐标对应的indexPath
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
    
    JWBoJianDetailsCommentModel *model = _CommentListArr[indexPath.row];
    
    _placeholderLabel.text = [NSString stringWithFormat:@"回复%@",model.user_nickname];
    [_CommentTextView becomeFirstResponder];
    _parent_id = [NSString stringWithFormat:@"%@",model.comment_id];;
    
//    NSLog(@"d但是开发快速打飞机；案例====>>%ld",indexPath.row);
}
- (void) keyboardWillHide:(NSNotification*)notification {
    
    
    _placeholderLabel.text = @"说点什么吧";
}
- (void)yuyingPlay:(UIButton *)sender{
    
    JWBoJianDetailsCommentModel *model = _CommentListArr[sender.tag - 3000];
    
    NSURL *url = [NSURL URLWithString:model.comment_content];
    
//    NSLog(@"-=-=-=>>>>%@",model.comment_content);
    
    [self playAudioWithURL:url];
    
    
}
- (void)playAudioWithURL:(NSURL *)url{
//    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
//    NSError * error;
    
    self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
    self.audioPlayer.delegate = self;
    //设置初始音量大小
    // avAudioPlayer.volume = 1;
    
    //设置音乐播放次数  -1为一直循环
    self.audioPlayer.numberOfLoops = -1;
    BOOL success = [self.audioPlayer play];
    if (success) {
        NSLog(@"播放成功");
    }else{
        NSLog(@"播放失败");
    }
}

- (NSString*)getURLFromStr:(NSString *)string {
    NSError *error;
    //可以识别url的正则表达式
    NSString *regulaStr = @"((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)";
    
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regulaStr
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];
    
    NSArray *arrayOfAllMatches = [regex matchesInString:string
                                                options:0
                                                  range:NSMakeRange(0, [string length])];
    
    //NSString *subStr;
    //    NSMutableArray *arr=[[NSMutableArray alloc] init];
    //
    NSString* substringForMatch;
    for (NSTextCheckingResult *match in arrayOfAllMatches){
        substringForMatch = [string substringWithRange:match.range];
        //        [arr addObject:substringForMatch];
    }
    return substringForMatch;
}
#pragma mark -网络请求
//博见内容
-(void)makeUrl_post_postInfo{
    [[DDNetworkManagerDate makeUrl_post_postInfoWithtoken:k_user_token post_id:[NSString stringWithFormat:@"%@",_post_id]] post_RequestFinshSuccess:^(id responseObject) {
        if ([self requestFinshCode:responseObject isShowMessage:YES] == 1) {
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
            _ListmodelArr = [NSMutableArray new];
            NSDictionary *data = [responseObject objectForKey:kRequsetDataKey];
            //转模型
            _SnapshotModel = [BJDynamicSnapshotModel yy_modelWithDictionary:data];
            
            if ([_SnapshotModel.post_type integerValue] == 2) {
                NSString *htmls = [NSString stringWithFormat:@"<html> \n"
                                   "<head> \n"
                                   "<style type=\"text/css\"> \n"
                                   "body {font-size:15px;}\n"
                                   "</style> \n"
                                   "</head> \n"
                                   "<body>"
                                   "<script type='text/javascript'>"
                                   "window.onload = function(){\n"
                                   "var $img = document.getElementsByTagName('img');\n"
                                   "for(var p in  $img){\n"
                                   " $img[p].style.width = '100%%';\n"
                                   "$img[p].style.height ='auto'\n"
                                   "}\n"
                                   "}"
                                   "</script>%@"
                                   "</body>"
                                   "</html>",_SnapshotModel.post_content];
                [_JiaWenWebView loadHTMLString:htmls baseURL:nil];
            }
            
        }
        [self.tableView reloadData];
    } failure:^(id errorObject) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        [self showBottomMessag:@"网络请求失败"];
    }];
}
//点赞
-(void)makeUrl_postBJ_postPraise{
    [[DDNetworkManagerDate makeUrl_postBJ_postPraiseWithtoken:k_user_token post_id:[NSString stringWithFormat:@"%@",_post_id]] post_RequestFinshSuccess:^(id responseObject) {
        
        if ([self requestFinshCode:responseObject isShowMessage:YES] == 1) {
            NSInteger num = [_SnapshotModel.praise_num integerValue];
            self.DetailsCell.praise_num.text = [NSString stringWithFormat:@"%ld",num + 1];
            
            [self makeUrl_postBJ_praiseList];
 
        }
//        [self.tableView reloadData];
    } failure:^(id errorObject) {
        [self showBottomMessag:@"网络请求失败"];
    }];
}
//点赞列表
-(void)makeUrl_postBJ_praiseList{
    [[DDNetworkManagerDate makeUrl_postBJ_praiseListWithtoken:k_user_token post_id:[NSString stringWithFormat:@"%@",_post_id]] post_RequestFinshSuccess:^(id responseObject) {

//        NSLog(@"-=-=>>%@",responseObject);
        if ([self requestFinshCode:responseObject isShowMessage:YES] == 1) {
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
            //            _ListmodelArr = [NSMutableArray new];
            NSArray *data = [responseObject objectForKey:kRequsetDataKey];
            //转模型
            _praiseListArr = [NSMutableArray array];
            [data enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                
//                BJDynamicSnapshotModel *model = [BJDynamicSnapshotModel yy_modelWithDictionary:obj];
                [_praiseListArr addObject:[obj objectForKey:@"user_nickname"]];
                
                if ([[NSString stringWithFormat:@"%@",[obj objectForKey:@"user_id"]] isEqualToString:k_user_uid]) {
                    
                }
            }];
        }
        NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:1];
        [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
//        [self.tableView reloadData];
    } failure:^(id errorObject) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        [self showBottomMessag:@"网络请求失败"];
    }];
}
//评论
-(void)makeUrl_postBJ_postComment{
    [[DDNetworkManagerDate makeUrl_postBJ_postCommentWithtoken:k_user_token post_id:[NSString stringWithFormat:@"%@",_post_id] parent_id:_parent_id comment_type:_comment_type comment_content:_CommentTextView.text] post_RequestFinshSuccess:^(id responseObject) {
//        NSLog(@"-=-=>>%@",responseObject);
        if ([self requestFinshCode:responseObject isShowMessage:YES] == 1) {
            
            _CommentTextView.text = @"";
            _parent_id = nil;
            _placeholderLabel.text = @"说点什么吧";
            _placeholderLabel.hidden = NO;
            
            [self makeUrl_postBJ_commentList];
        }
    } failure:^(id errorObject) {
        
        [self showBottomMessag:@"网络请求失败"];
    }];
}
//评论列表
-(void)makeUrl_postBJ_commentList{
    [[DDNetworkManagerDate makeUrl_postBJ_commentListWithtoken:k_user_token post_id:[NSString stringWithFormat:@"%@",_post_id] page:[NSString stringWithFormat:@"%d",_page]] post_RequestFinshSuccess:^(id responseObject) {
        NSLog(@"-=-=>>%@",responseObject);
        if ([self requestFinshCode:responseObject isShowMessage:YES] == 1) {
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
            NSArray *data = [responseObject objectForKey:kRequsetDataKey];
            NSMutableArray *arr = [NSMutableArray array];
            [data enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                JWBoJianDetailsCommentModel *model = [JWBoJianDetailsCommentModel yy_modelWithDictionary:obj];
                [arr addObject:model];
            }];
            if (_page == 1) {
                self.CommentListArr = arr.mutableCopy;
            }else{
                [self.CommentListArr addObjectsFromArray:arr];
            }
//            _CommentListArr = arr.mutableCopy;
        }
        
        NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:2];
        [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
//        [self.tableView reloadData];
    } failure:^(id errorObject) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        [self showBottomMessag:@"网络请求失败"];
    }];
}
//礼物列表
-(void)makeUrl_postBJ_giftList{
    [[DDNetworkManagerDate makeUrl_postBJ_giftListWithtoken:k_user_token] post_RequestFinshSuccess:^(id responseObject) {
        NSLog(@"-=-=>>%@",responseObject);
        if ([self requestFinshCode:responseObject isShowMessage:YES] == 1) {
            NSArray *data = [responseObject objectForKey:kRequsetDataKey];
            NSMutableArray *arr = [NSMutableArray array];
            [data enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                JWBoJianGiftModel *model = [JWBoJianGiftModel yy_modelWithDictionary:obj];
                [arr addObject:model];
            }];
            _giftListArr = arr.mutableCopy;
            [self giftBGViewBuild];
        }
    } failure:^(id errorObject) {
        [self showBottomMessag:@"网络请求失败"];
    }];
}
//赠送礼物
-(void)makeUrl_postBJ_toGift{
    [[DDNetworkManagerDate makeUrl_postBJ_toGiftWithtoken:k_user_token user_id:k_user_uid gift_id:[NSString stringWithFormat:@"%@",_GiftModel.gift_id] post_id:[NSString stringWithFormat:@"%@",_SnapshotModel.post_id]] post_RequestFinshSuccess:^(id responseObject) {
        NSLog(@"-=-=>>%@",responseObject);
        if ([self requestFinshCode:responseObject isShowMessage:YES] == 1) {
           
        }
    } failure:^(id errorObject) {
        [self showBottomMessag:@"网络请求失败"];
    }];
}

- (void)textViewDidChange:(UITextView *)textView{
    
    if (textView.text.length > 0) {
        
        _placeholderLabel.hidden = YES;
        
    }else{
        
        _placeholderLabel.hidden = NO;
    }
    
}
-(NSMutableArray *)ListmodelArr{
    if (!_ListmodelArr) {
        _ListmodelArr = [NSMutableArray array];
    }
    return _ListmodelArr;
}
-(NSMutableArray *)CommentListArr{
    if (!_CommentListArr) {
        _CommentListArr = [NSMutableArray array];
    }
    return _CommentListArr;
}
-(NSMutableArray *)giftListArr{
    if (!_giftListArr) {
        _giftListArr = [NSMutableArray array];
    }
    return _giftListArr;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
